package com.cpp.db;

import java.sql.*;

/**
 * 封装ResultSet。当查询数据量超大时使用DBUtils.iterate方法返回此对象，避免调用query方法导致内存消耗过大。
 * @author lighthu
 */
public class ResultIterator {
	private ResultSet resultSet;
	private Statement statement;
	private Connection connection;
	private int columnCount;
	private ResultRow currentRow;
	
	/**
	 * Constructor。
	 * @param rs 封装的ResultSet对象
	 * @param stmt 产生ResultSet的Statement对象
	 * @param conn 产生ResultSet的Connection对象
	 * @throws Exception
	 */
	public ResultIterator(ResultSet rs, Statement stmt, Connection conn) throws Exception {
		resultSet = rs;
		statement = stmt;
		connection = conn;
		columnCount = rs.getMetaData().getColumnCount();
	}
	
	/**
	 * 移动光标到下一条记录。
	 */
	public boolean next() {
		try {
			currentRow = null;
			return resultSet.next();
		} catch (Exception e) {
			return false;
		}
	}
	
	/**
	 * 取得当前记录的数据。
	 */
	public ResultRow getRowData() {
		if (currentRow != null) {
			return currentRow;
		}
		ResultRow row = new ResultRow(columnCount);
		for (int i = 0; i < columnCount; i++) {
			try {
				row.setColumn(i + 1, resultSet.getObject(i + 1));
			} catch (Exception e) {
			}
		}
		currentRow = row;
		return row;
	}
	
	/**
	 * 释放资源，使用完后必须调用。
	 */
	public void close() {
		try {
			resultSet.close();
		} catch (Exception e) {
		}
		try {
			statement.close();
		} catch (Exception e) {
		}
		try {
			DBUtils.releaseConnection(connection);
		} catch (Exception e) {
		}
	}
}
